package com.naiterui.ehp.ps.sms.factory;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.naiterui.ehp.bp.utils.lang.ConfigUtil;
import com.naiterui.ehp.ps.sms.utils.HttpRequestUtils;
import com.naiterui.ehp.ps.sms.utils.constants.SmsConstants;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 红豆电信短信
 * 
 * @author yangfuya
 * @since 2022/1/24
 */
@Slf4j
public class HongdouApi {

    /**
     * api请求基础路径
     */
    private static final String BASE_URL = ConfigUtil.getString(SmsConstants.API_HONGDOU_BASE_URL);
    /**
     * app key
     */
    private static final String APP_KEY = ConfigUtil.getString(SmsConstants.API_HONGDOU_KEY);
    /**
     * app secret
     */
    private static final String APP_SECRET = ConfigUtil.getString(SmsConstants.API_HONGDOU_SECRET);
    /**
     * app code
     */
    private static final String APP_CODE = ConfigUtil.getString(SmsConstants.API_HONGDOU_CODE);

    /**
     * 一对一相同内容群发
     */
    public static final String SMS_BATCH = BASE_URL + "/sms/batch/v1";
    /**
     * 一对一内容群发
     */
    public static final String SMS_DISTINCT = BASE_URL + "/sms/distinct/v1";

    /**
     * 红豆电信短信单条信息发送
     * 
     * @param phone
     *            手机号
     * @param content
     *            拼接好的短信内容
     * @return
     */
    public static String siggleSend(String phone, String content) {
        JSONObject param = new JSONObject();
        param.put("appkey", APP_KEY);
        param.put("appcode", APP_CODE);
        String timestamp = System.currentTimeMillis() + "";
        param.put("timestamp", timestamp);
        try {
            String sign = md5(APP_KEY + APP_SECRET + timestamp);
            param.put("sign", sign);
        } catch (Exception e) {
            log.info("发送短信时发送异常：{}", e.getMessage());
            return null;
        }

        // 批量发送的手机号和短信内容
        JSONObject sms = new JSONObject();
        sms.put("phone", phone);
        sms.put("msg", content);
        JSONArray smsList = new JSONArray();
        smsList.add(sms);
        param.put("sms", smsList);

        // 请求header头
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json;charset=utf-8");
        headers.put("Accept", "application/json;");
        // 调用红豆短信API短信接口
        log.info("调用红豆短信API短信接口: url : {}, params : {}, header: {}", SMS_DISTINCT, param.toJSONString(),
            JSONUtil.toJsonStr(headers));
        String result = HttpRequestUtils.doPostBasicAndHeader(SMS_DISTINCT, param.toJSONString(), headers);
        return result;
    }

    private static String md5(String param) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] md5Byte = md5.digest(param.getBytes("utf8"));
        String result = byteToHex(md5Byte);
        return result;
    }

    private static String byteToHex(byte[] md5Byte) {
        String result = "";
        StringBuilder sb = new StringBuilder();
        for (byte each : md5Byte) {
            int value = each & 0xff;
            String hex = Integer.toHexString(value);
            if (value < 16) {
                sb.append("0");
            }
            sb.append(hex);
        }
        result = sb.toString();
        return result;
    }

    public static int byte4ToInteger(byte[] b, int offset) {
        return (0xff & b[offset]) << 24 | (0xff & b[offset + 1]) << 16 | (0xff & b[offset + 2]) << 8
            | (0xff & b[offset + 3]);
    }

}
